// pages/livelist/livelist.js
const app = getApp();
var dateUtil = require('../util/util.js');
var loginStatus = true;
Page({
  firstGet: 1,
  /**
   * 页面的初始数据
   */
  data: {
    livelist: {},
    courses: {},
    studentRole: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('获取用户信息，并刷新视频列表');
    this.getPromission();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉刷视频列表')
    this.getPromission();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  /**进入视频页面 */
  goto_live: function (event) {
    console.log("进入视频页面")
    console.log(event)
    //进入视频，传id 
    var liveid = event.currentTarget.id
    var playF = event.currentTarget.dataset.playf;
    app.globalData.currentlive.liveId = liveid
    app.globalData.currentlive.playF = playF

    console.log("=========liveList======")
    console.log(playF)
    //跳转到视频页面
    wx.request({
      url: 'https://www.zuoye123.com/i_cloudmate/stulivelessonlist/xcxgotoLesson',
      data: {
        userId: app.globalData.userId,
        liveId: liveid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log('获取的视频列表json如下：')
        console.log(res.data)

        if (res.data.errorCode != 0) {
          // wx.showModal({
          //   title: '',
          //   content: '暂时没有视频信息，下拉页面刷新试试',
          //   showCancel: false
          // })
        } else {
          wx.navigateTo({
            url: '/pages/live/live',
          })
        }
      }
    })
  },

  /**获取视频列表 */
  getLiveList: function () {
    var that = this;

    wx.request({
      url: 'https://www.zuoye123.com/i_cloudmate/stulivelessonlist/xcxgetlivelist',
      data: {
        userId: app.loginUser.userId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log('获取列表json如下：')
        console.log(res.data)

        if (res.data.errorCode != 0) {
          that.setData({
            errortip: '获取列表失败，下拉刷新重新获取！'
          })
        } else {
          //对日期格式化处理
          if (app.loginUser.userRole == 100) {

            that.setData({
              livelist: [],
              courses: res.data.courses,
              studentRole: 100
            })
          }
          else {

            for (var i = 0; i < res.data.liveList.length; i++) {
              var live = res.data.liveList[i]
              var startTime = dateUtil.formats(live.startTime, 'M/D h:m');
              var endTime = dateUtil.formats(live.endTime, 'M/D h:m');
              live.startTime = startTime;
              live.endTime = endTime;
            }
            that.setData({
              livelist: res.data.liveList,
              courses: [],
              studentRole: 1
            })
          }

        }
        wx.stopPullDownRefresh();
      }
    })
  }
  ,
  // thisPageGetUser: function () {
  //   var that = this;

  //   if (app.loginUser) {
  //     console.log('livelist.onShow()===loginUser========yes')
  //     console.log(app.loginUser.loginId)
  //     console.log(app.loginUser.loginName)
  //     console.log(app.loginUser.userName)
  //     console.log(app.loginUser.userId)
  //     console.log('请求视频列表')
  //     console.log("app.globalData.userId=" + app.loginUser.userId)
  //     that.getLiveList();
  //   } else {
  //     console.log('livelist.onShow()===loginUser========NO');
  //   }
  // },
  goLogin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        console.log('code=' + res.code);
        console.log('res.errMsg=' + res.errMsg);
        var code = res.code;
        if (res.code) {
          wx.getUserInfo({
            withCredentials: true,
            success: function (res) {
              console.log(res);
              that.getNeededUserInfo(code, res.encryptedData, res.iv);
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg);
        }
      },
      fail: function () {
        console.log('获取用户信息失败')
      }
    })
  }
  ,
  /**
   * 后台获取用户信息
   * 
   */
  getNeededUserInfo: function (code, enc, iv) {
    console.log('getNeededUserInfo.code=' + code);
    var that = this;
    wx.request({
      url: 'https://www.zuoye123.com/n_cloudmate/weixin/login',
      data: {
        code: code,
        encryptedData: enc,
        iv: iv
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        // 可以返回前端需要的用户信息（包括unionid、openid、user_id等）
        console.log('=====res==========');
        console.log(res);
        if (res.data.status == 1) {
          console.log(res.data.userInfo);
          if (res.data.userInfo.unionId != '') {
            console.log(res.data.userInfo.unionId)
            // 成功获取到unionid
            app.loginUser = res.data.userInfo;
            app.globalData.unionid = res.data.userInfo.unionId;
            app.globalData.userInfo = res.data.userInfo;
            //请求获取userId
            that.getUserId();
          }
          else {
            that.getPromission();
          }
        } else {
          console.log(res)


        }

      },
      fail: function () {
        console.log('系统错误')
      }
    })
  },
  //用户强制授权
  getPromission: function () {
    var that = this;
    if (!loginStatus) {
      wx.openSetting({
        success: function (data) {
          if (data) {
            if (data.authSetting["scope.userInfo"] == true) {
              loginStatus = true;
              wx.getUserInfo({
                withCredentials: true,
                success: function (data) {
                  console.info("2成功获取用户返回数据");
                  console.info(data.userInfo);
                  console.log(data)
                },
                fail: function () {
                  console.info("2授权失败返回数据");
                  that.getPromission();
                }
              });
            }
          }
        },
        fail: function () {
          console.info("设置失败返回数据");
        }
      });
    } else {
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.getUserInfo({
              withCredentials: true,
              success: function (data) {
                console.info("1成功获取用户返回数据");
                console.info(data);
                var iv = data.iv;
                var enc = data.encryptedData;
                that.getNeededUserInfo(res.code, enc, iv);
              },
              fail: function () {
                console.info("1授权失败返回数据");
                loginStatus = false;
                // 显示提示弹窗
                wx.showModal({
                  // title: '提示',
                  title: '请在微信授权页面点击允许，否则该小程序将无法使用，是否重新授权？',
                  confirmText: '重新授权',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    } else if (res.cancel) {
                      console.log('用户点击取消')

                    }
                    that.getPromission();
                  }
                });
              }
            });
          }
        }
      })
    }
  },

  //获取userId
  getUserId: function () {
    console.log('getUserId.unionid=' + app.loginUser.unionId)
    console.log('getUserId.unionid=' + app.globalData.unionid)
    var that = this;
    wx.request({
      url: 'https://www.zuoye123.com/n_cloudmate/weixin/wechat_get_userid',
      data: {
        unionid: app.globalData.unionid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (data) {
        console.log(data);
        if (data.data.errorCode == '10002') {
          that.getPromission();
        }

        if (data.data.errorCode == 'unbind') {
          console.log('用户未绑定账号！跳转中。。。');
          wx.navigateTo({
            url: '/pages/login/login',
          })
        }

        if (data.data.errorCode == 0) {
          console.log('获取账号成功，正在获取视频列表');
          app.globalData.userId = data.data.userId;
          console.log(data.data.loginUser);
          app.loginUser = data.data.loginUser[0];
          console.log("loginUser.userRole===" + app.loginUser.userRole);
          that.getLiveList();
        }
      }
    })
  }
  ,
  openFile: function (event) {
    console.log('----------------------------opendocument----------------------------')
    console.log(event);
    console.log(event.target.id)

    wx.getStorage({
      key: event.currentTarget.dataset.resid + "",
      success: function (res) {
        console.log('===================获取缓存成功！！！！！！！！===========================================')
        console.log(res.data);
        wx.downloadFile({
          // url: 'https://www.zuoye123.com/file/46830/resource/f87f7e148782fae551e4666172d2ead2-97760.pdf',
          url: res.data,
          success: function (res) {
            console.log(res)
            var filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: function (res) {
                console.log('打开文档成功')
              }
            })
          }
        })
      },
      fail: function (res) {
        console.log(res);
        wx.setStorage({
          key: event.currentTarget.dataset.resid + "",
          data: event.currentTarget.id,
          success: function (res) {
            console.log('异步保存成功')
            console.log(res);
          }
        });
        wx.downloadFile({
          url: event.currentTarget.id,
          success: function (res) {
            console.log(res)
            var filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: function (res) {
                console.log('打开文档成功')
              }
            })
          }
        })

      }
    })




    console.log('----------------------------opendocument----------------------------')

  }
})